<?php

namespace App\Http\Controllers;

use App\Http\Requests\SearchRequest;
use App\Http\Resources\AirportResource;
use App\Services\SearchServiceInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Throwable;

class AirportsSearchController extends Controller
{
    public function __construct(private readonly SearchServiceInterface $searchService)
    {
    }

    public function searchAction(SearchRequest $request): JsonResponse|AnonymousResourceCollection
    {
        $query = $request->get('query');

        try {
            $results = $this->searchService->search($query);
        } catch (Throwable $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }

        return AirportResource::collection($results);
    }
}
